package com.dangdi.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.dangdi.entity.PrintLine;
import com.dangdi.entity.PrintStyle;
import com.dangdi.service.ImportBookService;
import com.dangdi.sip2.SocketClientAct;
import com.dangdi.util.JavaRs232;
import com.dangdi.util.SocketClient2;
import com.dangdi.utils.TicketPrinter;

import com.gexin.fastjson.JSON;
import com.gexin.fastjson.JSONArray;
import com.gexin.fastjson.JSONObject;
import com.google.gson.Gson;
import cvr100demo.IdCardReader;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import util.*;

import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@CrossOrigin(allowCredentials = "true", maxAge = 3600)
public class ReaderDerviceController implements ApplicationRunner {
    @Resource
    ImportBookService service;
    RfidReader test = new RfidReader();
    ReaderCardDervice reader = new ReaderCardDervice();
    IdCardReader idCardReader = new IdCardReader();
    JavaRs232 javaRs232 = new JavaRs232();
    SocketClient2 socketClient2 = null;
    private String terminalPort = null;
    private int thisCount = 0;
    private int thisReaderCount = 0;
    Logger logger = LoggerFactory.getLogger(this.getClass());

    public String getTerminalPort() {
        return terminalPort;
    }

    public void setTerminalPort(String terminalPort) {
        this.terminalPort = terminalPort;
    }

    @ResponseBody
    @RequestMapping("OpenRfidReaderDervice")
    public Map<String, Object> OpenRfidReaderDervice(String ip) throws InterruptedException, IOException, URISyntaxException {
        Map<String, Object> map = new HashMap<String, Object>();
        int ct = 50;
        test.setActionType(-1);
        test.setRequestType("defualt");
        test.setReadCount(1);
        test.setAfi(-1);
        test.closeRfidDervice();
        while (test.getCode2() == -1) {
            Thread.sleep(100);
            if (test.getCode2() == 0) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        Thread t = new Thread(test);
        t.start();
        ct = 10;
        while (!test.isFlag()) {
            Thread.sleep(100);
            if (test.isFlag()) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        map.put("code", test.getCode());
        if (test.getCode() != 0) {
            map.put("code", -1);
            map.put("msg", "开启失败失败,错误代码：" + test.getCode());
            map.put("dervice_type", "RFID");
            return map;
        }
        map.put("msg", "开启成功");
        map.put("dervice_type", "RFID");
        return map;
    }

    @ResponseBody
    @RequestMapping("CloseRfidReaderDervice")
    public Map<String, Object> CloseRfidReaderDervice(String ip) throws InterruptedException, IOException, URISyntaxException {
        Map<String, Object> map = new HashMap<String, Object>();
        test.closeRfidDervice();
        int ct = 50;
        while (test.getCode2() == -1) {
            Thread.sleep(100);
            if (test.getCode2() == 0) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        map.put("code", test.getCode2());
        if (test.isFlag()) {
            map.put("code", -1);
            map.put("msg", "关闭失败,错误代码：" + test.getCode2());
            map.put("dervice_type", "RFID");
            return map;
        }
        map.put("msg", "关闭成功");
        map.put("dervice_type", "RFID");
        return map;
    }

    @ResponseBody
    @RequestMapping("getRfidReaderDerviceStatus")
    public Map<String, Object> getRfidReaderDerviceStatus(String ip) throws InterruptedException, IOException, URISyntaxException {
        Map<String, Object> map = new HashMap<String, Object>();
        if (!test.isFlag()) {
            map.put("code", -1);
            map.put("msg", "非读卡状态");
            map.put("dervice_type", "RFID");
            return map;
        }
        map.put("code", 0);
        map.put("msg", "读卡状态");
        map.put("dervice_type", "RFID");
        return map;
    }


    @ResponseBody
    @RequestMapping("OpenReaderCardDervice")
    public Map<String, Object> OpenReaderCardDervice() throws InterruptedException, IOException, URISyntaxException {
        Map<String, Object> map = new HashMap<String, Object>();
        reader.closeReaderDervice();
        int ct = 50;
        while (reader.getStatusCode() == 0) {
            Thread.sleep(100);
            if (reader.getStatusCode() == -1) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }

        Thread t = new Thread(reader);
        t.start();
        ct = 10;
        while (!reader.isFlag()) {
            Thread.sleep(100);
            if (reader.isFlag()) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        map.put("code", reader.getStatusCode());
        if (reader.getStatusCode() != 0) {
            map.put("code", -1);
            map.put("msg", "开启失败，错误代码:" + reader.getStatusCode());
            map.put("dervice_type", "reader");
        } else {
            map.put("code", 0);
            map.put("msg", "开启成功");
            map.put("dervice_type", "reader");
        }

        return map;
    }


    @ResponseBody
    @RequestMapping("OpenReaderCardDervice1")
    public String OpenReaderCardDervice1(@RequestParam("callback") String callback) throws InterruptedException, IOException, URISyntaxException {
        Map<String, Object> map = new HashMap<String, Object>();
        reader.closeReaderDervice();
        int ct = 50;
        while (reader.getStatusCode() == 0) {
            Thread.sleep(100);
            if (reader.getStatusCode() == -1) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }

        Thread t = new Thread(reader);
        t.start();
        ct = 10;
        while (!reader.isFlag()) {
            Thread.sleep(100);
            if (reader.isFlag()) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        map.put("code", reader.getStatusCode());
        if (reader.getStatusCode() != 0) {
            map.put("code", -1);
            map.put("msg", "开启失败，错误代码:" + reader.getStatusCode());
            map.put("dervice_type", "reader");
        } else {
            map.put("code", 0);
            map.put("msg", "开启成功");
            map.put("dervice_type", "reader");
        }
        Gson gson = new Gson();

        return callback + "(" + gson.toJson(map) + ")";
    }

    @ResponseBody
    @RequestMapping("CloseReaderCardDervice")
    public Map<String, Object> CloseReaderCardDervice(String ip) throws InterruptedException, IOException, URISyntaxException {
        Map<String, Object> map = new HashMap<String, Object>();
        reader.closeReaderDervice();
        int ct = 10;
        reader.setActionType(0);
        while (reader.isFlag()) {
            Thread.sleep(100);
            if (!reader.isFlag()) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        if (reader.getStatusCode() != 0) {
            map.put("code", reader.getStatusCode());
            map.put("msg", "关闭失败");
        }
        map.put("code", 0);
        map.put("msg", "关闭成功");
        map.put("dervice_type", "reader");
        return map;
    }

    @ResponseBody
    @RequestMapping("getReaderCardDervice")
    public Map<String, Object> getReaderCardDervice(String ip) throws InterruptedException, IOException, URISyntaxException {
        Map<String, Object> map = new HashMap<String, Object>();
        if (!reader.isFlag()) {
            map.put("code", -1);
            map.put("msg", "非读卡状态");
            map.put("dervice_type", "reader");
            return map;
        }
        map.put("code", 0);
        map.put("msg", "读卡状态");
        map.put("dervice_type", "reader");
        return map;
    }

    @ResponseBody
    @RequestMapping("getIDCardReaderDervice")
    public Map<String, Object> getIDCardReaderDervice(String ip) throws InterruptedException, IOException, URISyntaxException {
        Map<String, Object> map = new HashMap<String, Object>();

        if (!idCardReader.isFlag()) {
            map.put("code", -1);
            map.put("msg", "非读卡状态");
            map.put("dervice_type", "idCard");
            return map;
        }
        map.put("code", 0);
        map.put("msg", "读卡状态");
        map.put("dervice_type", "idCard");
        return map;
    }

    @ResponseBody
    @RequestMapping("openIDCardReaderDervice")
    public Map<String, Object> openIDCardReaderDervice(String ip) throws InterruptedException, IOException, URISyntaxException {
        Map<String, Object> map = new HashMap<String, Object>();
        idCardReader.closeIDCardDervice();
        int ct = 10;
        while (idCardReader.isFlag()) {
            Thread.sleep(100);
            if (!idCardReader.isFlag()) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        Thread t = new Thread(idCardReader);
        t.start();
        ct = 10;
        while (!idCardReader.isFlag()) {
            Thread.sleep(100);
            if (idCardReader.isFlag()) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        if (idCardReader.getRead_ContentCode() != 1) {
            map.put("code", -1);
            map.put("msg", "开启失败");
            map.put("dervice_type", "idCard");
            return map;
        }
        map.put("code", 0);
        map.put("msg", "开启成功");
        map.put("dervice_type", "idCard");
        return map;
    }

    @ResponseBody
    @RequestMapping("CloseIDCardReaderDervice")
    public Map<String, Object> CloseIDCardReaderDervice(String ip) throws InterruptedException, IOException, URISyntaxException {
        Map<String, Object> map = new HashMap<String, Object>();
        idCardReader.closeIDCardDervice();
        int ct = 10;
        while (idCardReader.isFlag()) {
            Thread.sleep(100);
            if (!idCardReader.isFlag()) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        map.put("code", 0);
        map.put("msg", "关闭成功");
        map.put("dervice_type", "idCard");
        return map;
    }

    @RequestMapping("manager")
    public String manager() {
        //配置文件绝对路径
        String filePath = System.getProperty("user.dir") + "\\conf.properties";
        //定义修改配置文件的工具类
        PropertiesUtils utils = new PropertiesUtils(filePath);
        if (!utils.getKeyValue("inited").equals("1")) {
            setTerminalPort(utils.getKeyValue("server.port"));
            return "admin";
        }
        return "manager";
    }

    @RequestMapping("BookDerviceSetting")
    public String BookDerviceSetting() {
        return "BookDerviceSetting";
    }

    @ResponseBody
    @RequestMapping("FindServiceIpAddres")
    public Map<String, Object> FindServiceIpAddres(String port) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        HttpClientUtil2 httpClientUtil = new HttpClientUtil2();
        String localIp = getLocalInfo();
        localIp = "172.16.0.0";
        map.put("locahostlIP", localIp);
        String serverIp = "";
        websokectHandler handler = new websokectHandler();
        for (int i = 1; i <= 255; i++) {
            serverIp = "http://" + localIp.substring(0, localIp.lastIndexOf(".") + 1) + i + ":" + port + "/DangD/getPortAndIp";
            HttpResponse response = null;
            map.put("checkIP", localIp.substring(0, localIp.lastIndexOf(".") + 1) + i);
            map.put("from", "FindServer");
            map.put("statusCode", "1");
            handler.onMessage(JSONObject.toJSONString(map));
            try {
                response = httpClientUtil.HttoPost(map, serverIp);
                if (response.getStatusLine().getStatusCode() == 200) {
                    JSONObject jo = (JSONObject) JSON.parse(EntityUtils.toString(response.getEntity()));
                    map.put("message", "已找到服务器");
                    map.put("ip", jo.get("ip"));
                    map.put("port", jo.get("port"));
                    map.put("statusCode", "0");
                    handler.onMessage(JSONObject.toJSONString(map));
                    return map;
                }
            } catch (URISyntaxException e) {
            } catch (IOException e) {
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        map.put("statusCode", "-1");
        return map;
    }

    public String getLocalInfo() {
        // TODO Auto-generated method stub
        InetAddress ia = null;
        String localip = "";
        try {
            ia = ia.getLocalHost();
            localip = ia.getHostAddress();
            return localip;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return localip;
    }

    @ResponseBody
    @RequestMapping(value = "PrintTicket", method = RequestMethod.POST)
    public Map<String, Object> PrintTicket(String header, String message) {
        Map<String, Object> map = new HashMap<String, Object>();
//    	 List<Object>dList=JSONArray.parseArray(data);
        //System.out.println(header);
        //System.out.println(message);
        //JSONArray hd=JSONArray.parseArray(header);
        //JSONArray ms=JSONArray.parseArray(message);
        //JSONObject jo=(JSONObject)hd.get(0);
        //JSONObject jo2=(JSONObject)ms.get(0);
        //JSONArray qq = (JSONArray) JSON.parse(header);
        //JSONArray ww = (JSONArray) JSON.parse(message);
        //System.out.println(qq.get(0));
        JSONArray hd = (JSONArray) JSONArray.parse(header);
        JSONArray ms = (JSONArray) JSONArray.parse(message);
        List<JSONObject> joList = new ArrayList<JSONObject>();
        List<JSONObject> joList2 = new ArrayList<JSONObject>();
        for (int i = 0; i < hd.size(); i++) {
            joList.add((JSONObject) hd.get(i));
        }
        for (int i = 0; i < ms.size(); i++) {
            joList2.add((JSONObject) ms.get(i));
        }
        //配置文件绝对路径
        String filePath = System.getProperty("user.dir") + "\\conf.properties";
        //定义修改配置文件的工具类
        PropertiesUtils utils = new PropertiesUtils(filePath);
//    	//创建打印行集合
        List<PrintLine> lines = new ArrayList<PrintLine>();
        List<String> lineStr = new ArrayList<String>();
        lineStr.add("========= " + joList.get(0).get("type") + "凭证  =========");
        lineStr.add("读者姓名：" + joList.get(0).get("reader_name"));
/*        lineStr.add("流 水 号 ：" + new Date().getTime());
        lineStr.add("终 端 号 ：" + utils.getKeyValue("terminalNumber"));*/
        lineStr.add("时间日期：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        for (int i = 0; i < joList2.size(); i++) {
            lineStr.add("...........................................................");
            lineStr.add("书    名：" + joList2.get(i).get("book_name"));
            lineStr.add("条    码：" + joList2.get(i).get("book_bar_code"));
            lineStr.add("书籍架位：" + joList2.get(i).get("book_weizhi"));
        }
        lineStr.add("*****************************************");
        lineStr.add("总    共：" + joList2.size() + " 本");
        lineStr.add("                         ");
        int heigth = 0;
        for (int i = 0; i < lineStr.size(); i++) {
            heigth = (i + 1) * 20;
            PrintLine printLine = new PrintLine();
            printLine.setLineX(5);

            printLine.setLineY((heigth));


            printLine.setLineStr(lineStr.get(i));
            lines.add(printLine);
        }
        //创建打印页面
        PrintStyle style = new PrintStyle();
        //设置内容
        style.setLine(lines);
        //设置打印数量
        style.setCopies(1);
        //打印页面高度
        style.setPageHeight(heigth + 13);
        //打印页面宽度
        style.setPageWidth(250);
        //页面坐标
        style.setPageX(0);
        style.setPageY(0);
        //把打印行集合添加到页面
        //定义一个打印类
        TicketPrinter printer = new TicketPrinter(style);
        //打印页面
        printer.printTicket(style);
        map.put("code", 0);
        map.put("msg", "打印成功");
        return map;
    }

    @ResponseBody
    @RequestMapping("getConfigParam")
    public Map<String, Object> getConfigFile(String param) throws FileNotFoundException {
        //方法返回值是一个map
        Map<String, Object> map = new HashMap<>();
        //配置文件绝对路径
        String filePath = System.getProperty("user.dir") + "\\conf.properties";
        //定义修改配置文件的工具类
        PropertiesUtils utils = new PropertiesUtils(filePath);
        //返回值中添加配置文件参数
        map.put(param, utils.getKeyValue(param));
        map.put("statusCode", 0);
        map.put("message", "成功");
        return map;
    }

    @ResponseBody
    @RequestMapping("updateConfigParam")
    public Map<String, Object> updateConfigParam(String paramKey, String paramValue) throws FileNotFoundException {
        //方法返回值是一个map
        Map<String, Object> map = new HashMap<>();
        //配置文件绝对路径
        String filePath = System.getProperty("user.dir") + "\\conf.properties";
        //定义修改配置文件的工具类
        PropertiesUtils utils = new PropertiesUtils(filePath);
        //定义一个map用来封装修改的参数
        Map<String, Object> params = new HashMap<>();
        //修改的参数里面添加内容
        params.put(paramKey, paramValue);
        //执行修改
        utils.writeProperties(paramKey, paramValue, false);
        //返回值中添加配置文件参数
        map.put("statusCode", 0);
        map.put("message", "成功");

        return map;
    }

    @ResponseBody
    @RequestMapping("insertConfigParam")
    public Map<String, Object> insertConfigParam(String paramKey, String paramValue) throws FileNotFoundException {
        //方法返回值是一个map
        Map<String, Object> map = new HashMap<>();
        //配置文件绝对路径
        String filePath = System.getProperty("user.dir") + "\\conf.properties";
        //定义修改配置文件的工具类
        PropertiesUtils utils = new PropertiesUtils(filePath);
        //追加参数
        utils.writeProperties(paramKey, paramValue, false);
        //返回值中添加配置文件参数
        map.put("statusCode", 0);
        map.put("message", "成功");
        return map;
    }

    @ResponseBody
    @RequestMapping("getConfigAllParam")
    public Map<String, Object> getConfigAllParam() throws FileNotFoundException {
        //方法返回值是一个map
        Map<String, Object> map = new HashMap<>();
        //配置文件绝对路径
        String filePath = System.getProperty("user.dir") + "\\conf.properties";
        //定义修改配置文件的工具类
        PropertiesUtils utils = new PropertiesUtils(filePath);
        //返回值中添加配置文件参数
        map.put("paramList", utils.getAllProperties());
        map.put("statusCode", 0);
        map.put("message", "成功");
        return map;
    }

    @ResponseBody
    @RequestMapping("removeConfigParam")
    public Map<String, Object> removeConfigParam() {
        //方法返回值是一个map
        Map<String, Object> map = new HashMap<>();
        //配置文件绝对路径
        String filePath = System.getProperty("user.dir") + "\\conf.properties";
        //定义修改配置文件的工具类
        PropertiesUtils utils = new PropertiesUtils(filePath);
        //返回值中添加配置文件参数
        utils.removeProperties("aaa");
        map.put("statusCode", 0);
        map.put("message", "成功");
        return map;
    }

    //修改终端端口好
    @ResponseBody
    @RequestMapping("updateTerminalPort")
    public Map<String, Object> updateTerminalPort(String port) {
        //方法返回值是一个map

        Map<String, Object> map = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        //配置文件绝对路径
        String filePath = System.getProperty("user.dir") + "\\conf.properties";
        //定义修改配置文件的工具类
        PropertiesUtils utils = new PropertiesUtils(filePath);
        setTerminalPort(utils.getKeyValue("server.port"));
        //返回值中添加配置文件参数
        param.put("server.port", port);
        utils.writeProperties("server.port", port, false);
        map.put("statusCode", 0);
        map.put("message", "成功");
        return map;
    }

    @ResponseBody
    @RequestMapping("getIPandPort")
    public Map<String, Object> getIPandPort(String port) throws UnknownHostException {
        //方法返回值是一个map
        Map<String, Object> map = new HashMap<>();
        //配置文件绝对路径
        String filePath = System.getProperty("user.dir") + "\\conf.properties";
        //定义修改配置文件的工具类
        PropertiesUtils utils = new PropertiesUtils(filePath);
        //返回值中添加配置文件参数
        map.put("port", utils.getKeyValue("server.port"));
        String is = null;
        is = InetAddress.getLocalHost().getHostAddress();
        map.put("ip", is);
        map.put("statusCode", 0);
        map.put("message", "成功");
        return map;
    }

    @RequestMapping("admin")
    public String admin() {
        String filePath = System.getProperty("user.dir") + "\\conf.properties";
        //定义修改配置文件的工具类
        PropertiesUtils utils = new PropertiesUtils(filePath);
        if (!utils.getKeyValue("inited").equals("1")) {
            setTerminalPort(utils.getKeyValue("server.port"));
            return "admin";
        }
        return "manager";
    }

    @ResponseBody
    @RequestMapping("getOldPort")
    public Map<String, Object> getOldPort() throws UnknownHostException {
        //方法返回值是一个map
        Map<String, Object> map = new HashMap<>();
        //配置文件绝对路径
        //定义修改配置文件的工具类
        //返回值中添加配置文件参数
        String is = null;
        is = InetAddress.getLocalHost().getHostAddress();
        map.put("ip", is);
        if (getTerminalPort() == null) {
            String filePath = System.getProperty("user.dir") + "\\conf.properties";
            //定义修改配置文件的工具类
            PropertiesUtils utils = new PropertiesUtils(filePath);
            map.put("port", utils.getKeyValue("server.port"));
        } else {
            map.put("port", getTerminalPort());
        }
        map.put("statusCode", 0);
        map.put("message", "成功");
        return map;
    }

    @ResponseBody
    @RequestMapping("finishInit")
    public Map<String, Object> finishInit() throws IOException, URISyntaxException {
        //方法返回值是一个map
        Map<String, Object> map = new HashMap<>();
        String filePath = System.getProperty("user.dir") + "\\conf.properties";
        //定义修改配置文件的工具类
        PropertiesUtils utils = new PropertiesUtils(filePath);
        Map<String, Object> params = new HashMap<>();
        params.put("inited", "1");
        utils.writeProperties("inited", "1", false);
        HttpClientUtil util = new HttpClientUtil();
        Map m = new HashMap();
        Map m2 = new HashMap();
        String is = null;
        is = InetAddress.getLocalHost().getHostAddress();
        m2.put("ip", is);
        m2.put("port", utils.getKeyValue("server.port"));
        m2.put("terminalSymbol", utils.getKeyValue("terminalSymbol"));
        m2.put("terminalNumber", utils.getKeyValue("terminalNumber"));
        m.put("data", JSON.toJSONString(m2));
        String server = "http://" + utils.getKeyValue("serverIP") + ":" + utils.getKeyValue("serverPort") + "/DangD/acceptIp";
        HttpResponse response = util.HttoPost(m, server);
        map.put("statusCode", 0);
        map.put("newPort", utils.getKeyValue("server.port"));
        map.put("message", "成功");
        String com = System.getProperty("user.dir") + "\\restart.bat";
        run_cmd("cmd /c start " + System.getProperty("user.dir") + "\\restart.bat");
        return map;
    }

    public String run_bat(String url) throws IOException {
        Runtime.getRuntime().exec(url);
        return "ok";
    }

    public void run_cmd(String strcmd) {
//
        Runtime rt = Runtime.getRuntime(); //Runtime.getRuntime()返回当前应用程序的Runtime对象
        Process ps = null;  //Process可以控制该子进程的执行或获取该子进程的信息。
        try {
            ps = rt.exec(strcmd);   //该对象的exec()方法指示Java虚拟机创建一个子进程执行指定的可执行程序，并返回与该子进程对应的Process对象实例。
            ps.waitFor();  //等待子进程完成再往下执行。
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        int i = ps.exitValue();  //接收执行完毕的返回值
        if (i == 0) {
            System.out.println("执行完成.");
        } else {
            System.out.println("执行失败.");
        }

        ps.destroy();  //销毁子进程
        ps = null;
    }

    @ResponseBody
    @RequestMapping("getAllDerviceStatus")
    public List<Map<String, Object>> getAllDerviceStatus() {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> idCardMap = new HashMap<String, Object>();
        Map<String, Object> RFIDMap = new HashMap<String, Object>();
        Map<String, Object> readerCardMap = new HashMap<String, Object>();
        //身份证读卡器
        if (idCardReader.getRead_ContentCode() == -1) {
            idCardMap.put("code", -1);
            idCardMap.put("msg", "非读卡状态");
            idCardMap.put("type", "idCardReader");
        } else {
            idCardMap.put("code", 1);
            idCardMap.put("msg", "读卡状态");
            idCardMap.put("type", "idCardReader");
        }
        //RFID
        if (test.getCode2() == 0) {
            RFIDMap.put("code", -1);
            RFIDMap.put("msg", "非读卡状态");
            RFIDMap.put("type", "RDIDReader");
        } else if (test.getCode() == 0) {
            RFIDMap.put("code", 0);
            RFIDMap.put("msg", "读卡状态");
            RFIDMap.put("type", "RDIDReader");
        } else {
            RFIDMap.put("code", -1);
            RFIDMap.put("msg", "非读卡状态");
            RFIDMap.put("type", "RDIDReader");
        }
        //读者卡
        if (reader.getStatusCode() != 0) {
            readerCardMap.put("code", -1);
            readerCardMap.put("msg", "非读卡状态");
            readerCardMap.put("type", "readerCard");
        } else {
            readerCardMap.put("code", 0);
            readerCardMap.put("msg", "读卡状态");
            readerCardMap.put("type", "readerCard");
        }
        list.add(readerCardMap);
        list.add(RFIDMap);
        list.add(idCardMap);
        return list;
    }

    @ResponseBody
    @RequestMapping("managerLogin")
    public String managerLogin(String adminName, String adminPassword) {
        Map<String, Object> map = new HashMap<>();
        String filePath = System.getProperty("user.dir") + "\\conf.properties";
        //定义修改配置文件的工具类
        PropertiesUtils utils = new PropertiesUtils(filePath);
        if (!adminName.equals(utils.getKeyValue("adminName")) || !adminPassword.equals(utils.getKeyValue("adminPassword"))) {
            return "-1";
        }
        return "0";
    }

    @ResponseBody
    @RequestMapping("jieshu")
    public Map<String, Object> jieshu(String uIDList) throws InterruptedException {
        Map<String, Object> map = new HashMap<>();
        test.closeRfidDervice();
        test.setActionType(0);
        int ct = 10;
        while (test.isFlag()) {
            Thread.sleep(100);
            if (!test.isFlag()) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        Thread t = new Thread(test);
        t.start();
        ct = 10;
        while (!test.isFlag()) {
            Thread.sleep(100);
            if (test.isFlag()) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        while (test.isFlag()) {
            Thread.sleep(100);
            if (!test.isFlag()) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        map.put("afiNotChangedList", test.getAfiNotChangedList());
        map.put("bookCount", test.getBookCount());
        map.put("afiList", test.getAfiList());
        System.out.println(map);
        return map;
    }

    @ResponseBody
    @RequestMapping("huanshu")
    public Map<String, Object> huanshu(String uIDList) throws InterruptedException {
        Map<String, Object> map = new HashMap<>();
        test.closeRfidDervice();
        test.setActionType(1);
        int ct = 10;
        while (test.isFlag()) {
            Thread.sleep(100);
            if (!test.isFlag()) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        Thread t = new Thread(test);
        t.start();
        ct = 10;
        while (!test.isFlag()) {
            Thread.sleep(100);
            if (test.isFlag()) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        while (test.isFlag()) {
            Thread.sleep(100);
            if (!test.isFlag()) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        map.put("afiNotChangedList", test.getAfiNotChangedList());
        map.put("bookCount", test.getBookCount());
        map.put("afiList", test.getAfiList());
        test.closeRfidDervice();
        System.out.println(map);
        return map;
    }

    @ResponseBody
    @RequestMapping("startImportBook")
    public Map<String, Object> startImportBook() throws InterruptedException, IOException, URISyntaxException {
        thisCount = 0;
        Map<String, Object> map = new HashMap<String, Object>();
        int ct = 50;
        test.setActionType(2);
        test.setRequestType("no");
        test.setReadCount(1);
        test.setAfi(-1);
        test.closeRfidDervice();
        while (test.getCode2() == -1) {
            Thread.sleep(100);
            if (test.getCode2() == 0) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        Thread t = new Thread(test);
        t.start();
        ct = 10;
        while (!test.isFlag()) {
            Thread.sleep(100);
            if (test.isFlag()) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        map.put("code", test.getCode());
        if (test.getCode() != 0) {
            map.put("code", -1);
            map.put("msg", "开启失败失败,错误代码：" + test.getCode());
            map.put("dervice_type", "RFID");
            return map;
        }
        map.put("msg", "开启成功");
        map.put("dervice_type", "RFID");
        return map;
    }

    @RequestMapping("importBook")
    public String importBook() {
        return "importBook";
    }


    @ResponseBody
    @RequestMapping("insertRfidAndCode")
    public Map<String, Object> insertRfidAndCode(String rfid, String code) {
        Map<String, Object> map = new HashMap<>();
        if (service.checkCodeAndRfid(code, rfid).size() > 0) {
            map.put("allCoutn", service.getAllcount());
            map.put("thisCount", thisCount);
            map.put("todayCount", service.getTodayCount());
            map.put("statusCode", -1);
            map.put("message", "请勿重复录入");
            return map;
        }
        if (service.checkCode(code).size() > 0) {
            map.put("allCoutn", service.getAllcount());
            map.put("thisCount", thisCount);
            map.put("todayCount", service.getTodayCount());
            map.put("statusCode", -1);
            map.put("message", "条形码重复");
            return map;
        }

        if (service.checkRfid(rfid).size() > 0) {
            map.put("allCoutn", service.getAllcount());
            map.put("thisCount", thisCount);
            map.put("todayCount", service.getTodayCount());
            map.put("statusCode", -1);
            map.put("message", "RFID重复");
            return map;
        }
        service.insertBokk(code, rfid);
        thisCount++;
        map.put("allCoutn", service.getAllcount());
        map.put("thisCount", thisCount);
        map.put("todayCount", service.getTodayCount());
        map.put("statusCode", 0);
        map.put("message", "录入成功");
        return map;
    }


    @ResponseBody
    @RequestMapping("getCoutn")
    public Map<String, Object> insertRfidAndCode() {
        Map<String, Object> map = new HashMap<>();
        map.put("allCoutn", service.getAllcount());
        map.put("thisCount", thisCount);
        map.put("todayCount", service.getTodayCount());
        return map;
    }

    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @RequestMapping("statistic")
    public String statistic() {
        return "statistic";
    }

    @RequestMapping("importReader")
    public String importReader(ModelMap map) {
        map.put("reader", service.getOneReaderForNotReaderCardID());
        return "importReader";
    }

    @ResponseBody
    @RequestMapping("checkAllParam")
    public Map<String, Object> checkAllParam() {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        map.put("checkCodeLength", service.checkCodeLength());
        map.put("checkRepeat", service.checkRepeat());
        map.put("checkRepeatCode", service.checkRepeatCode());
        map.put("checkRepeatRfid", service.checkRepeatRfid());
        map2.put("code", 0);
        map2.put("msg", "获取成功");
        map2.put("count", 99999);
        map2.put("data", map);
        return map;
    }

    @ResponseBody
    @RequestMapping("quchong")
    public Map<String, Object> quchong() {
        Map<String, Object> map = new HashMap<>();
        service.quChong();
        map.put("statusCode", 0);
        map.put("msg", "去重成功!");
        return map;
    }

    @ResponseBody
    @RequestMapping("quchongCode")
    public Map<String, Object> quchongCode() {
        Map<String, Object> map = new HashMap<>();
        service.quChongCode();
        map.put("statusCode", 0);
        map.put("msg", "去重成功!");
        return map;
    }

    @ResponseBody
    @RequestMapping("quchongRfid")
    public Map<String, Object> quchongRfid() {
        Map<String, Object> map = new HashMap<>();
        service.quChongRfid();
        map.put("statusCode", 0);
        map.put("msg", "去重成功!");
        return map;
    }

    @ResponseBody
    @RequestMapping("updateByCode")
    public Map<String, Object> updateByCode(String code, String rfid) {
        Map<String, Object> map = new HashMap<>();
        service.UpdateByCode(code, rfid);
        map.put("statusCode", 0);
        map.put("msg", "修改成功");
        return map;
    }

    @ResponseBody
    @RequestMapping("updateByRfid")
    public Map<String, Object> updateByRfid(String code, String rfid) {
        Map<String, Object> map = new HashMap<>();
        service.UpdateByRfid(code, rfid);
        map.put("statusCode", 0);
        map.put("msg", "修改成功");
        return map;
    }

    @ResponseBody
    @RequestMapping("checkCode")
    public Map<String, Object> checkCode(String code) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "获取成功");
        map.put("count", 99999);
        map.put("data", service.checkCode(code));
        return map;
    }

    @ResponseBody
    @RequestMapping("checkRfid")
    public Map<String, Object> checkRfid(String rfid) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "获取成功");
        map.put("count", 99999);
        map.put("data", service.checkRfid(rfid));
        return map;
    }

    @ResponseBody
    @RequestMapping("getOneReaderForNotReaderCardID")
    public Map<String, Object> getOneReaderForNotReaderCardID() {
        return service.getOneReaderForNotReaderCardID();
    }

    @ResponseBody
    @RequestMapping("updateReaderByReader_id")
    public Map<String, Object> updateReaderByReader_id(@RequestParam Map<String, Object> reader) {
        Map<String, Object> map = new HashMap<>();
        if (service.checkReader_rfid(reader.get("reader_rfid").toString()) > 0) {
            map.put("statusCode", -1);
            map.put("msg", "读者卡号重复");
            map.put("NotUpdatedReaderCount", service.NotUpdatedReaderCount());
            map.put("updatedReaderCount", service.updatedReaderCount());
            map.put("AllReaderCount", service.AllReaderCount());
            map.put("thisReaderCount", thisReaderCount);
            return map;
        }
        service.updateReaderByReader_id(reader);
        thisReaderCount++;
        map.put("statusCode", 0);
        map.put("msg", "添加成功");
        map.put("NotUpdatedReaderCount", service.NotUpdatedReaderCount());
        map.put("updatedReaderCount", service.updatedReaderCount());
        map.put("AllReaderCount", service.AllReaderCount());
        map.put("thisReaderCount", thisReaderCount);
        return map;
    }

    @ResponseBody
    @RequestMapping("getAllReaderCount")
    public Map<String, Object> getAllReaderCount() {
        Map<String, Object> map = new HashMap<>();
        map.put("statusCode", 0);
        map.put("msg", "获取成功");
        map.put("NotUpdatedReaderCount", service.NotUpdatedReaderCount());
        map.put("updatedReaderCount", service.updatedReaderCount());
        map.put("AllReaderCount", service.AllReaderCount());
        map.put("thisReaderCount", thisReaderCount);
        map.put("readerRoleList", service.readerRoleList());
        map.put("readerStatusList", service.readerStatusList());
        return map;
    }

    @ResponseBody
    @RequestMapping("startImportReader")
    public Map<String, Object> startImportReader() throws InterruptedException, IOException, URISyntaxException {
        Map<String, Object> map = new HashMap<String, Object>();
        reader.closeReaderDervice();
        reader.setActionType(1);
        int ct = 50;
        while (reader.getStatusCode() == 0) {
            Thread.sleep(100);
            if (reader.getStatusCode() == -1) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        Thread t = new Thread(reader);
        t.start();
        ct = 10;
        while (!reader.isFlag()) {
            Thread.sleep(100);
            if (reader.isFlag()) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        map.put("code", reader.getStatusCode());
        if (reader.getStatusCode() != 0) {
            map.put("code", -1);
            map.put("msg", "开启失败，错误代码:" + reader.getStatusCode());
            map.put("dervice_type", "reader");
        } else {
            map.put("code", 0);
            map.put("msg", "开启成功");
            map.put("dervice_type", "reader");
        }
        return map;
    }

    @ResponseBody
    @RequestMapping("upload")
    public Map<String, Object> upload(MultipartFile file) throws IOException, BiffException {
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> insertedList = new ArrayList<String>();
        List<String> notInsertedList = new ArrayList<String>();
        System.out.println(file.getOriginalFilename());
        InputStream stream = file.getInputStream();
        Workbook workBook = Workbook.getWorkbook(stream);
        Sheet sheet = workBook.getSheet(0);
        System.out.println("row=" + sheet.getRows());
        System.out.println("colom=" + sheet.getColumns());
        for (int k = 0; k < sheet.getColumns(); k++) {
            for (int i = 0; i < sheet.getColumn(k).length - 1; i++) {
                String sb = "";
                if (!sheet.getCell(k, i).getContents().equals("")) {
                    sb = "insert into bookshelf values(id=null,school='" + sheet.getCell(k, 0).getContents() + "',tag='" + sheet.getCell(k, i + 1).getContents() + "')";
                    service.insertExlUpload(sheet.getCell(k, 0).getContents(), sheet.getCell(k, i + 1).getContents());
                }
                System.out.println(sb);
            }
        }
        return map;
    }

    @RequestMapping("excellUploadPage")
    public String excellUploadPage() {
        return "excellUploadPage";
    }

    @RequestMapping("bookshelfPage")
    public String bookshelfPage() {
        return "bookshelfPage";
    }

    @ResponseBody
    @RequestMapping("getSchoolList")
    public Map<String, Object> getSchoolList() {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "获取成功");
        map.put("count", 99999);
        map.put("data", service.getSchoolList());
        return map;
    }

    @ResponseBody
    @RequestMapping("getTagListBySchool")
    public Map<String, Object> getTagListBySchool(String school) {
        Map<String, Object> map = new HashMap<>();
        test.closeRfidDervice();
        map.put("code", 0);
        map.put("msg", "获取成功");
        map.put("count", 99999);
        map.put("data", service.getTagListBySchool(school));
        return map;
    }

    @ResponseBody
    @RequestMapping("comScanOneRFID")
    public Map<String, Object> comScanOneRFID() throws InterruptedException, IOException, URISyntaxException {
        System.out.println("进来了");
        Map<String, Object> map = new HashMap<String, Object>();
        int ct = 50;
        test.setActionType(3);
        test.closeRfidDervice();
        while (test.getCode2() == -1) {
            Thread.sleep(100);
            if (test.getCode2() == 0) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        Thread t = new Thread(test);
        t.start();
        ct = 10;
        while (!test.isFlag()) {
            Thread.sleep(100);
            if (test.isFlag()) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        map.put("code", test.getCode());
        if (test.getCode() != 0) {
            map.put("code", -1);
            map.put("msg", "开启失败失败,错误代码：" + test.getCode());
            map.put("dervice_type", "RFID");
            return map;
        }
        map.put("msg", "开启成功");
        map.put("dervice_type", "RFID");
        return map;
    }

    @ResponseBody
    @RequestMapping("startfindingBookShelf")
    public Map<String, Object> startfindingBookShelf(String school, String tag, String cengRFID) throws InterruptedException, IOException, URISyntaxException {
        thisCount = 0;
        Map<String, Object> map = new HashMap<String, Object>();
        int ct = 50;
        test.setActionType(4);
        test.setSchool(school);
        test.setTag(tag);
        test.setCengRFID(cengRFID);
        System.out.println(school);
        System.out.println(tag);
        System.out.println(cengRFID);
        test.closeRfidDervice();
        while (test.getCode2() == -1) {
            Thread.sleep(100);
            if (test.getCode2() == 0) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        Thread t = new Thread(test);
        t.start();
        ct = 10;
        while (!test.isFlag()) {
            Thread.sleep(100);
            if (test.isFlag()) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        map.put("code", test.getCode());
        if (test.getCode() != 0) {
            map.put("code", -1);
            map.put("msg", "开启失败失败,错误代码：" + test.getCode());
            map.put("dervice_type", "RFID");
            return map;
        }
        map.put("msg", "开启成功");
        map.put("dervice_type", "RFID");
        return map;
    }

    @ResponseBody
    @RequestMapping("deleteShelfByBookRfid")
    public int deleteShelfByBookRfid(String book) {
        return service.deleteBookSheflByBookRfid(book);
    }

    @ResponseBody
    @RequestMapping("startSendSocket")
    public Map<String, Object> startSendSocket(String host, int port, String requestType, String requestUrl) throws InterruptedException, IOException, URISyntaxException {
        thisCount = 0;
        Map<String, Object> map = new HashMap<String, Object>();
        int ct = 50;
        test.setSocketHost(host);
        test.setSocketProt(port);
        test.setRequestType(requestType);
        test.setRequestUrl(requestUrl);
        test.setActionType(5);
        test.closeRfidDervice();
        test.setReadCount(1);
        test.setAfi(-1);
        while (test.getCode2() == -1) {
            Thread.sleep(100);
            if (test.getCode2() == 0) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        Thread t = new Thread(test);
        t.start();
        ct = 10;
        while (!test.isFlag()) {
            Thread.sleep(100);
            if (test.isFlag()) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        map.put("code", test.getCode());
        if (test.getCode() != 0) {
            map.put("code", -1);
            map.put("msg", "开启失败失败,错误代码：" + test.getCode());
            map.put("dervice_type", "RFID");
            return map;
        }
        map.put("msg", "开启成功");
        map.put("dervice_type", "RFID");
        return map;
    }

    @ResponseBody
    @RequestMapping("sendSocket")
    public void sendSocket(String msg) {
        SocketClientAct clientAct = new SocketClientAct("172.16.0.4", 6666);
        clientAct.sendMessage(msg);
    }

    //扫描可用的串口列表（基本上没用）
    @RequestMapping("scanComPortList")
    @ResponseBody
    public Map<String, Object> scanComPortList() {
        logger.info("scanComPortList方法进来了");
        logger.info("定义一个map");
        Map<String, Object> map = new HashMap<String, Object>();
        logger.info("newJavaRs232工具类");
        logger.info("调用扫描的方法");
        logger.info("扫描方法执行完毕，返回给页面");
        return map;
    }

    //打开串口
    //  参数列表：
    //      comName:串口名字[COM1][COM2]
    //      comRate:波特率（9600 就行）
    //      conData：数据位（8 就行）
    //      comStop：停止位（1 就行）
    //      comParity：校验和（0 为none ，0就行）
    @RequestMapping("openComPortList")
    @ResponseBody
    public Map<String, Object> openComPortList(String comName, int comRate, int conData, int comStop, int comParity) {
        logger.info("scanComPortList方法进来了");
        logger.info("定义一个map");
        Map<String, Object> map = new HashMap<String, Object>();
        logger.info("newJavaRs232工具类");
        logger.info("调用打开的方法");
        Thread t = new Thread(javaRs232);
        t.start();
        logger.info("事务启动了");

//        map.put("comPortLost",javaRs232.scanPorts());
        javaRs232.openSerialPort(comName, comRate, conData, comStop, comParity);
        logger.info("打开方法执行完毕，返回给页面");
        return map;
    }

    //关闭串口（注意：关闭串口之前向串口发送关闭继电器的消息）
    // 这里只不过是关闭与电路板的连接，并不是继电器
    @RequestMapping("closeSerialPort")
    @ResponseBody
    public Map<String, Object> closeSerialPort() {
        logger.info("scanComPortList方法进来了");
        logger.info("定义一个map");
        Map<String, Object> map = new HashMap<String, Object>();
        logger.info("newJavaRs232工具类");
        logger.info("调用关闭的方法");
        javaRs232.closeSerialPort();
        javaRs232.setFlag(false);
        logger.info("关闭方法执行完毕，返回给页面");
        return map;
    }

    //向串口传数据(打开/关闭门)
    // 数据均为16进制的int类型
    @RequestMapping("sendPortMessage")
    @ResponseBody
    public Map<String, Object> sendPortMessage(int message) {
        // 发送消息
        //   int message=0XA1;
        //A1     打开1号继电器    返回 11
        //A2     打开2号继电器    返回 13
        // ..........
        //B1     关闭1号继电器    返回 12
        //B2     关闭2号继电器    返回 14
        // ..........
        // 获取状态 （门的状态）
        // 01   1号输入端通电
        // F1   1号输入端断开
        //.........
        // 04   4号输入端通断
        // F4   4号输入端断开
        // 继电器通电时间不能超过5秒    继电器通电时间不能超过5秒   继电器通电时间不能超过5秒（重要的事情说三遍）
        logger.info("scanComPortList方法进来了");
        Map<String, Object> map = new HashMap<String, Object>();
        logger.info("发送消息的方法");
        javaRs232.sendDataToSeriaPort(message);
        return map;
    }

    //启动socket客户端
    //  port socket服务器端口好（暂时写死）
    //  host    socket服务器ip（暂时写死）
    @RequestMapping("runSocketClient")
    @ResponseBody
    public Map<String, Object> runSocketClient(String host, int port) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        if (socketClient2 == null) {
            try {
                socketClient2 = new SocketClient2(host, port);
                test.setSocketClient2(socketClient2);
            } catch (IOException e) {
//              e.printStackTrace();
                map.put("msg", "未找到socket服务器，请检查");
                map.put("code", -1);
                return map;
            }
            new Thread(socketClient2).start();
            map.put("msg", "socket客户端启动成功");
            map.put("code", 0);
            return map;
        } else {
            if (socketClient2.isServerConnetion()) {
                map.put("msg", "不能重复启动");
                map.put("code", -1);
                return map;
            } else {
                System.out.println("线程没在跑啊老小弟");
                socketClient2 = new SocketClient2(host, port);
                test.setSocketClient2(socketClient2);
                new Thread(socketClient2).start();
                map.put("msg", "socket客户端启动成功");
                map.put("code", 0);
                return map;
            }
        }
    }

    //关闭socket客户端
    @RequestMapping("closeSocketClient")
    @ResponseBody
    public Map<String, Object> closeSocketClient() throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        if (socketClient2 != null) {
            socketClient2.closeSocketClient();
        }
        socketClient2 = null;
        map.put("msg", "socket客户端关闭成功");
        map.put("code", 0);
        return map;
    }

    //发送socket消息
    @RequestMapping("sendSocketmessage")
    @ResponseBody
    public Map<String, Object> runSocketClient(String msg) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        if (socketClient2 == null || !socketClient2.isServerConnetion()) {
            map.put("msg", "socket客户端未启动，请您先启动");
            map.put("code", -1);
            return map;
        } else {
//            socketClient2.SendThread("1720181218    114523AOTJDQDXX|ABE0040150A1F0AAA0|AY5AZF33E" + "\r");
//            socketClient2.SendThread(msg);
            socketClient2.SendThread(msg+"\r");
            map.put("msg", "消息已发送，能不能发出去？服务器能不能收到这个得看你的运气了");
            map.put("code", 0);
        }
        if (socketClient2.isServerConnetion() == false) {
            System.out.println("服务器不可用");
        }
        return map;
    }

    //////////////层位绑定
    @ResponseBody
    @RequestMapping("insertShujiaBangding")
    public Map<String, Object> insertShujiaBangding(String rfid, String code, String weizhima, String shujiahao, String cengweihao, String lieweihao) {
        Map<String, Object> map = new HashMap<>();
        if (service.getBookLocationRfidCountByRfid(rfid) > 0) {
            map.put("allCoutn", service.getBookLocationAllCount());
            map.put("thisCount", thisCount);
            map.put("todayCount", service.getBookLocationTodayCount());
            map.put("statusCode", -1);
            map.put("message", "RFID重复");
            return map;
        }
        if (service.getBookLocationRfidCountByCode(code) > 0) {
            map.put("allCoutn", service.getBookLocationAllCount());
            map.put("thisCount", thisCount);
            map.put("todayCount", service.getBookLocationTodayCount());
            map.put("statusCode", -1);
            map.put("message", "条形码重复");
            return map;
        }
        if (service.insertBookLocation(weizhima, rfid, shujiahao, cengweihao, lieweihao, code) != 1) {
            map.put("statusCode", -1);
            map.put("message", "绑定失败");
            return map;
        }
        thisCount++;
        map.put("allCoutn", service.getBookLocationAllCount());
        map.put("thisCount", thisCount);
        map.put("todayCount", service.getBookLocationTodayCount());
        map.put("statusCode", 0);
        map.put("message", "绑定成功");
        return map;
    }

    @RequestMapping("jiaweibangding")
    public String jiaweibangding() {
        return "jiaweibangding";
    }

    //发送socket消息
    @RequestMapping("thisCountSet0")
    @ResponseBody
    public Map<String, Object> thisCountSet0() throws InterruptedException {
        Map<String, Object> map = new HashMap<String, Object>();
        test.closeRfidDervice();
        int ct = 50;
        while (test.getCode2() == -1) {
            Thread.sleep(100);
            if (test.getCode2() == 0) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        map.put("code", test.getCode2());
        if (test.isFlag()) {
            map.put("code", -1);
            map.put("msg", "关闭失败,错误代码：" + test.getCode2());
            map.put("dervice_type", "RFID");
            return map;
        }
        map.put("msg", "关闭成功");
        map.put("dervice_type", "RFID");
        map.put("code", 0);
        thisCount = 0;
        return map;
    }

    //新的开启设备的方法
    @RequestMapping("startRfidRead1")
    @ResponseBody
    public String startRfidRead1(@RequestParam("callback") String callback, String comType, String comName, String reader_name, String requestType, String rete, String requestUrl, String host, int prot, int readCount, int afi) throws InterruptedException {
        test.setComType(comType);
        test.setComName(comName);
        test.setReader_name(reader_name);
        test.setRequestUrl(requestType);
        test.setRete(rete);
        test.setRequestType(requestType);
        test.setRequestUrl(requestUrl);
        test.setHost(host);
        test.setPort(prot);
        test.setReadCount(readCount);
        test.setAfi(afi);
        Map<String, Object> map = new HashMap<String, Object>();
        int ct = 50;
        test.setActionType(-1);
        test.closeRfidDervice();
        Thread t = new Thread(test);
        t.start();
        map.put("code", test.getCode());
        Gson gson = new Gson();
        if (test.getCode() != 0) {
            map.put("code", -1);
            map.put("msg", "开启失败失败,错误代码：" + test.getCode());
            map.put("dervice_type", "RFID");
            return callback + "(" + gson.toJson(map) + ")";
        }
        map.put("msg", "开启成功");
        map.put("dervice_type", "RFID");


        return callback + "(" + gson.toJson(map) + ")";
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("正在初始化socket客户端和串口通信");
        String filePath = System.getProperty("user.dir") + "\\conf.properties";
        PropertiesUtils utils = new PropertiesUtils(filePath);
        try {
            socketClient2 = new SocketClient2(utils.getKeyValue("serverIP"), Integer.parseInt(utils.getKeyValue("serverPort")));
            new Thread(socketClient2).start();
//            socketClient2=new SocketClient2(utils.getKeyValue("serverIP"),4444);
        } catch (IOException e) {
//                e.printStackTrace();
            logger.info("找不到客户端");
        }
        test.setSocketClient2(socketClient2);
        logger.info("socket客户端启动成功");
//        Thread t=new Thread(javaRs232);
//        t.start();
////        map.put("comPortLost",javaRs232.scanPorts());
//        javaRs232.openSerialPort(utils.getKeyValue("comName"),Integer.parseInt(utils.getKeyValue("comRate")),Integer.parseInt(utils.getKeyValue("conData")),Integer.parseInt(utils.getKeyValue("comStop")),Integer.parseInt(utils.getKeyValue("comParity")));
        logger.info("打开方法执行完毕，返回给页面");
        System.out.println("串口通信启动了");
    }

    //新的开启设备的方法
    @RequestMapping("startRfidRead")
    @ResponseBody
    public Map<String, Object> startRfidRead(String comType, String comName, String reader_name, String requestType, String rete, String requestUrl, String host, int prot, int readCount, int afi) throws InterruptedException {
        test.setComType(comType);
        test.setComName(comName);
        test.setReader_name(reader_name);
        test.setRequestUrl(requestType);
        test.setRete(rete);
        test.setRequestType(requestType);
        test.setRequestUrl(requestUrl);
        test.setHost(host);
        test.setPort(prot);
        test.setReadCount(readCount);
        test.setAfi(afi);
        Map<String, Object> map = new HashMap<String, Object>();
        int ct = 50;
        test.setActionType(-1);
        test.closeRfidDervice();
        Thread t = new Thread(test);
        t.start();
        map.put("code", test.getCode());
        Gson gson = new Gson();
        if (test.getCode() != 0) {
            map.put("code", -1);
            map.put("msg", "开启失败失败,错误代码：" + test.getCode());
            map.put("dervice_type", "RFID");
            return map;
        }
        map.put("msg", "开启成功");
        map.put("dervice_type", "RFID");
        return map;
    }

    @RequestMapping("shangjia")
    public String shangjia() {
        return "shangjia";
    }


    @ResponseBody
    @RequestMapping("startPandian")
    public Map<String, Object> startPandian() throws InterruptedException, IOException, URISyntaxException {
        Map<String, Object> map = new HashMap<String, Object>();
        int ct = 50;
        test.setActionType(6);
        test.setRequestType("defualt");
        test.setReadCount(1);
        test.setAfi(-1);
        test.closeRfidDervice();
        Thread t = new Thread(test);
        t.start();
        ct = 10;
        while (!test.isFlag()) {
            Thread.sleep(100);
            if (test.isFlag()) {
                break;
            }
            ct--;
            if (ct == 0) {
                break;
            }
        }
        map.put("code", test.getCode());
        if (test.getCode() != 0) {
            map.put("code", -1);
            map.put("msg", "开启失败失败,错误代码：" + test.getCode());
            map.put("dervice_type", "RFID");
            return map;
        }
        map.put("msg", "开启成功");
        map.put("dervice_type", "RFID");
        return map;
    }

    @RequestMapping("closeChrome")
    public String closeChrome() {
        run_cmd("C:\\Windows\\System32\\taskkill -f -t -im chrome.exe");
        return "";
    }

    @ResponseBody
    @RequestMapping("pachong")
    public void pacong() throws IOException, URISyntaxException, InterruptedException {
        HttpClientUtil2 httpClientUtil2 = new HttpClientUtil2();
        Map<String, Object> params = new HashMap<String, Object>();
        JSONObject criteria = new JSONObject();
        JSONObject detail = new JSONObject();
        Map<String, Object> detailParam = new HashMap<String, Object>();
        detail.put("product_name", "");
        criteria.put("searchtype", "manufacturer");
        criteria.put("cartype", "passenger");
        criteria.put("manufacturer", "Manufacturer");
        criteria.put("model", "Model");
        criteria.put("engine_type", "Enginetype");
        criteria.put("engine_power", "Enginepower");
        params.put("criteria", criteria);
        HttpResponse response = httpClientUtil2.HttoPost(params, "http://video.total-app.com.cn/lubadvisor/getData.php");
        String str = EntityUtils.toString(response.getEntity());
        //制造商
        JSONArray manufacturerArray = JSON.parseArray(str);
        System.out.println(manufacturerArray);
        JSONObject manufacturerObject = new JSONObject();
        //车型
        JSONArray modelArray = new JSONArray();
        JSONObject modelObject = new JSONObject();
        //燃油类型
        JSONArray engine_typeArray = new JSONArray();
        JSONObject engine_typeObject = new JSONObject();
        //排量
        JSONArray engine_powerArray = new JSONArray();
        JSONObject engine_powerObject = new JSONObject();
        //润滑油
        JSONArray productArray = new JSONArray();
        JSONObject productObject = new JSONObject();
        //详情
        JSONArray detailArray = new JSONArray();
        JSONObject detailObject = new JSONObject();
        System.out.println("请求状态码=" + response.getStatusLine().getStatusCode());
        for (int i = 0; i < manufacturerArray.size(); i++) {
            manufacturerObject = (JSONObject) manufacturerArray.get(i);
//			System.out.println(manufacturerObject.get("manufacturer").toString());
            criteria.put("searchtype", "model");
            criteria.put("manufacturer", manufacturerObject.get("manufacturer").toString());
            params.put("criteria", criteria);
            response = httpClientUtil2.HttoPost(params, "http://video.total-app.com.cn/lubadvisor/getData.php");
            modelArray = JSONArray.parseArray(EntityUtils.toString(response.getEntity()));
            for (int i1 = 0; i1 < modelArray.size(); i1++) {
                modelObject = (JSONObject) modelArray.get(i1);
                criteria.put("searchtype", "engine_type");
                criteria.put("manufacturer", manufacturerObject.get("manufacturer").toString());
                criteria.put("model", modelObject.get("model").toString());
                params.put("criteria", criteria);
                response = httpClientUtil2.HttoPost(params, "http://video.total-app.com.cn/lubadvisor/getData.php");
                engine_typeArray = JSONArray.parseArray(EntityUtils.toString(response.getEntity()));
                for (int i2 = 0; i2 < engine_typeArray.size(); i2++) {
                    engine_typeObject = (JSONObject) engine_typeArray.get(i2);
                    criteria.put("searchtype", "engine_power");
                    criteria.put("manufacturer", manufacturerObject.get("manufacturer").toString());
                    criteria.put("model", modelObject.get("model").toString());
                    criteria.put("engine_type", engine_typeObject.get("engine_type"));
                    params.put("criteria", criteria);
                    response = httpClientUtil2.HttoPost(params, "http://video.total-app.com.cn/lubadvisor/getData.php");
                    engine_powerArray = JSONArray.parseArray(EntityUtils.toString(response.getEntity()));
                    for (int i3 = 0; i3 < engine_powerArray.size(); i3++) {
                        engine_powerObject = (JSONObject) engine_powerArray.get(i3);
//						criteria.put("searchtype","passenger");
                        criteria.remove("searchtype");
                        criteria.put("engine_type", engine_typeObject.get("engine_type").toString());
                        criteria.put("engine_power", engine_powerObject.get("engine_power").toString());
                        criteria.put("model", modelObject.get("model").toString());
                        criteria.put("manufacturer", manufacturerObject.get("manufacturer").toString());
                        params.put("criteria", criteria);
//						{"cartype":"passenger","engine_type":"Gasoline","engine_power":"1.6","model":"BEST","manufacturer":"中国一汽"}
//						{"cartype":"passenger","engine_type":"Gasoline","engine_power":"1.6","model":"BEST","manufacturer":"中国一汽"}
                        response = httpClientUtil2.HttoPost(params, "http://video.total-app.com.cn/lubadvisor/getProduct.php");
                        productArray = JSONArray.parseArray(EntityUtils.toString(response.getEntity()));
                        for (int i4 = 0; i4 < productArray.size(); i4++) {
                            productObject = (JSONObject) productArray.get(i4);
//                            System.out.println("===================================================");
//                            System.out.println(productObject);
//                            System.out.println("===================================================");
                            detail.put("product_name", productObject.get("product_total_lub_2").toString());
                            detailParam.put("criteria", detail);
                            response = httpClientUtil2.HttoPost(detailParam, "http://video.total-app.com.cn/lubadvisor/getProductDetail.php");
                            str = EntityUtils.toString(response.getEntity(), "GBK");
                            System.out.println("=======================================================");
                            System.out.println("制造商=" + manufacturerObject.get("manufacturer").toString() + ":");
                            System.out.println("车型=" + modelObject.get("model").toString() + ",");
                            System.out.println("燃油=" + engine_typeObject.get("engine_type").toString());
                            System.out.println("排量=" + engine_powerObject.get("engine_power").toString());
                            System.out.println("最佳产品=" + productObject.get("product_total_lub_1").toString());
                            System.out.println("适用产品=" + productObject.get("product_total_lub_2").toString());
                            if (productObject.get("product_total_transmission")!=null){
                                String biansu=productObject.get("product_total_transmission").toString();
                                if (!biansu.equals("")){
                                    System.out.println("变速箱油产品="+biansu);
                                    service.insertYou(manufacturerObject.get("manufacturer").toString(),modelObject.get("model").toString(),engine_powerObject.get("engine_power").toString(),biansu);
                                }
                            }
//                            str = decodeUnicode(str);
//                            str = str.replaceAll("<br>", "");
                            System.out.println("===================================================");
//							System.out.println(str);
//                            System.out.println("===================================================");
//                            String productDetail = "";
//                            String title = "";
//                            String itenm = "";
//                            if (str.indexOf("productDetail") > -1 && !productObject.get("product_total_lub_2").toString().equals("")) {
//                                str = str.substring(str.indexOf("productDetail") + 15, str.length());
//                                productDetail = str.substring(0, str.indexOf("</p>") - 1);
//                                if (productDetail.indexOf("<h3>") > -1) {
//                                    title = productDetail.substring(productDetail.indexOf("<h3>") + 4, productDetail.indexOf("</h3>")).trim();
//                                }
//                                productDetail = productDetail.substring(productDetail.indexOf("<p>") + 3, productDetail.length()).trim();
//                                if (str.indexOf("<ul>") > -1) {
//                                    itenm = str.substring(str.indexOf("<ul>") + 4, str.indexOf("</ul>")).trim();
//                                }
//                            }
//                            System.out.println("说明标题=" + title);
//                            System.out.println("说明内容=" + productDetail);
//                            System.out.println("特点=" + itenm);
//                            System.out.println("=======================================================");

//                            service.inserPachongdate(manufacturerObject.get("manufacturer").toString(), modelObject.get("model").toString(), engine_typeObject.get("engine_type").toString(), engine_powerObject.get("engine_power").toString(), productObject.get("product_total_lub_1").toString(), productObject.get("product_total_lub_2").toString(), null, productDetail, title, itenm);
//							System.out.println(str);
//							str=str.substring(str.indexOf("</p>")+4,str.length());
//							System.out.println("===================");
//							System.out.println(str);
                        }
                    }
                }
            }
        }
        System.out.println("程序执行完毕");
    }

    public static String decodeUnicode(String theString) {
        char aChar;
        int len = theString.length();
        StringBuffer outBuffer = new StringBuffer(len);
        for (int x = 0; x < len; ) {
            aChar = theString.charAt(x++);
            if (aChar == '\\') {
                aChar = theString.charAt(x++);
                if (aChar == 'u') {
                    // Read the xxxx
                    int value = 0;
                    for (int i = 0; i < 4; i++) {
                        aChar = theString.charAt(x++);
                        switch (aChar) {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                throw new IllegalArgumentException(
                                        "Malformed   \\uxxxx   encoding.");
                        }

                    }
                    outBuffer.append((char) value);
                } else {
                    if (aChar == 't')
                        aChar = '\t';
                    else if (aChar == 'r')
                        aChar = '\r';
                    else if (aChar == 'n')
                        aChar = '\n';
                    else if (aChar == 'f')
                        aChar = '\f';
                    outBuffer.append(aChar);
                }
            } else
                outBuffer.append(aChar);
        }
        return outBuffer.toString();
    }
//    @ResponseBody
//    @RequestMapping("json")
//    public List<Map<String,Object>>json(){
//        List<String> manufacturer=service.getManufacturer();
//
//
//        List<Map<String,Object>> data=new ArrayList<>();
//        for (int i=0;i<manufacturer.size();i++){
//            Map<String,Object> map=new HashMap<>();
//            map.put("name",manufacturer.get(i));
//            map.put("value",Pinyin.getPingYin(manufacturer.get(i)));
//            List<String> mode=new ArrayList<>();
//            mode=service.getModel(manufacturer.get(i));
//            List<Map<String,Object>> data2=new ArrayList<>();
//            for (int k=0;k<mode.size();k++){
//                Map<String,Object> map2=new HashMap<>();
//                map2.put("name",mode.get(k));
//                map2.put("value",Pinyin.getPingYin(mode.get(k)));
//                List<String>engine_type=service.getEngine_type(manufacturer.get(i),mode.get(k));
//                List<Map<String,Object>> data3=new ArrayList<>();
//                Map<String,Object>map3=new HashMap<>();
//                for (int j=0;j<engine_type.size();j++){
//                    map3.put("name",engine_type.get(j));
//                    map3.put("value",Pinyin.getPingYin(engine_type.get(j)));
//                    //排油量
//                    List<String>engine_power=service.getEngine_power(manufacturer.get(i),mode.get(k),engine_type.get(j));
////                    System.out.println(engine_power);
//                    List<Map<String,Object>> data4=new ArrayList<>();
//                    for (int z=0;z<engine_power.size();z++){
//                        Map<String,Object>map4=new HashMap<>();
//                        map4.put("name",engine_power.get(z));
//                        map4.put("value",Pinyin.getPingYin(engine_power.get(z)));
////                        System.out.println(manufacturer.get(i)+mode.get(k)+engine_type.get(j)+engine_power.get(z));
//                        map4.put("data",service.getDataByFourParam(manufacturer.get(i),mode.get(k),engine_type.get(j),engine_power.get(z)));
//                        data4.add(map4);
//                    }
//                    map3.put("engine_power",data4);
//                    System.out.println(map3);
//                    data3.add(map3);
//                }
//                map2.put("engine_type",data3);
//                data2.add(map2);
//            }
//            map.put("model",data2);
//            data.add(map);
//        }
//        return data;
//    }

    @ResponseBody
    @RequestMapping("json")
    public List<Map<String, Object>> json() {
        List<String> manufacturer = service.getManufacturer();
        List<Map<String, Object>> data = new ArrayList<>();
        for (int i = 0; i < manufacturer.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("name", manufacturer.get(i).trim());
            map.put("value", Pinyin.getPingYin(manufacturer.get(i)));
            List<String> mode = new ArrayList<>();
            mode = service.getModel(manufacturer.get(i));
            List<Map<String, Object>> data2 = new ArrayList<>();
            for (int k = 0; k < mode.size(); k++) {
                Map<String, Object> map2 = new HashMap<>();
                map2.put("name", mode.get(k));
                map2.put("value", Pinyin.getPingYin(mode.get(k)));
                List<String> engine_power = service.getEngine_power(manufacturer.get(i), mode.get(k));
                List<Map<String, Object>> data3 = new ArrayList<>();
//                for (int j = 0; j < engine_power.size(); j++) {
//                    Map<String, Object> map3 = new HashMap<>();
//                    map3.put("name", engine_power.get(j));
////                    map3.put("model",Pinyin.getPingYin(mode.get(k)));
//                    map3.put("value", Pinyin.getPingYin(engine_power.get(j)));
//
////                        System.out.println(manufacturer.get(i)+mode.get(k)+engine_type.get(j)+engine_power.get(z));
//                    map3.put("data", service.getDataByFourParam(manufacturer.get(i), mode.get(k), engine_power.get(j)));
////                    System.out.println(map3);
//                    data3.add(map3);
//                }
                map2.put("power", data3);
                data2.add(map2);
            }
            map.put("model", data2);
            data.add(map);
        }
        System.out.println(JSON.toJSONString(data));
        return data;
    }

    @RequestMapping("pachong2")
    @ResponseBody
    public void pachong2() throws IOException, URISyntaxException, InterruptedException {
        HttpClientUtil2 httpClientUtil2 = new HttpClientUtil2();
        Map<String,Object>params=new HashMap<>();
        params.put("iswx",0);
        HttpResponse response = httpClientUtil2.httpGet("https://upkeep.vchangyi.com/front/brand/list?iswx=0");
        String str = EntityUtils.toString(response.getEntity());
        JSONObject jo=JSONObject.parseObject(str);
        JSONObject jo1= (JSONObject) jo.get("response");
        JSONArray jo2= (JSONArray) jo1.get("list");
        JSONArray zhizaoshang =new JSONArray();
        List<Map<String,Object>>model=new ArrayList<>();
        List<Map<String,Object>>power=new ArrayList<>();
        List<Map<String,Object>>nianfen=new ArrayList<>();
        for (int i=0;i<jo2.size();i++){
            JSONObject jo3= (JSONObject) jo2.get(i);
            JSONArray jo4= (JSONArray) jo3.get("data");
            for (int k=0;k<jo4.size();k++){
                JSONObject jo5= (JSONObject) jo4.get(k);
                System.out.println("制造商="+jo5.get("name").toString());
                 response = httpClientUtil2.httpGet("https://upkeep.vchangyi.com/front/car/models_by_brand?iswx=0&brandName="+jo5.get("name").toString());
                str = EntityUtils.toString(response.getEntity());
                JSONObject jo6= JSONObject.parseObject(str);
                JSONArray jo7= (JSONArray) jo6.get("response");
                for (int j=0;j<jo7.size();j++){
                    System.out.println("车型="+jo7.get(j).toString());
                    response = httpClientUtil2.httpGet("https://upkeep.vchangyi.com/front/car/spec_list?iswx=0&brandName="+URLEncoder.encode(jo5.get("name").toString())+"&models="+URLEncoder.encode(jo7.get(j).toString()));
                    str = EntityUtils.toString(response.getEntity());
                    JSONObject jo8= JSONObject.parseObject(str);
                    JSONObject jo9= (JSONObject) jo8.get("response");
                    JSONArray jo10= (JSONArray) jo9.get("specList");
                    for (int z=0;z<jo10.size();z++){
                        JSONObject jo11= (JSONObject) jo10.get(z);

                        response = httpClientUtil2.httpGet("https://upkeep.vchangyi.com/front/car/get_year?iswx=0&brandName="+URLEncoder.encode(jo5.get("name").toString())+"&models="+URLEncoder.encode(jo7.get(j).toString())+"&salesName="+URLEncoder.encode(jo11.get("salesName").toString()));
                        str = EntityUtils.toString(response.getEntity());
                        JSONObject jo12= JSONObject.parseObject(str);
                        JSONArray jo13= (JSONArray) jo12.get("response");
                        for (int t=0;t<jo13.size();t++){

                            response = httpClientUtil2.httpGet("https://upkeep.vchangyi.com/front/car/get_recommend?iswx=0&brandName="+URLEncoder.encode(jo5.get("name").toString())+"&models="+URLEncoder.encode(jo7.get(j).toString())+"&salesName="+URLEncoder.encode(jo11.get("salesName").toString())+"&modelYear="+URLEncoder.encode(jo13.get(t).toString()));
                            str = EntityUtils.toString(response.getEntity());
                            JSONObject jo14= JSONObject.parseObject(str);
                            JSONObject jo15= (JSONObject) jo14.get("response");
//                            System.out.println("levelId="+jo15.get("levelId"));
                            Map<String,Object>pm=new HashMap<>();
                            pm.put("iswx",0);
                            pm.put("km","");
                            pm.put("levelId",jo15.get("levelId").toString());

                            response = httpClientUtil2.HttoPost(pm,"https://upkeep.vchangyi.com/front/car/by_mileage");
                            str = EntityUtils.toString(response.getEntity());
                            JSONObject jo16= JSONObject.parseObject(str);
                            JSONObject jo17= (JSONObject) jo16.get("response");
                            JSONArray jo18=new JSONArray();
                            JSONObject jo19=new JSONObject();
                            if (jo17.get("engineOil").toString().substring(0,1).equals("[")){
                                jo18= (JSONArray) jo17.get("engineOil");
                            }else {

                                jo19= (JSONObject) jo17.get("engineOil");
                                System.out.println("用量="+jo19.get("filling"));
                                System.out.println("年份="+jo13.get(t));
                                System.out.println("最佳="+jo19.get("high"));
                                System.out.println("其次="+jo19.get("lower"));
                                service.InsertPC(jo5.get("name").toString(),jo7.get(j).toString(),jo11.get("salesName").toString(),jo13.get(t).toString(),jo15.get("levelId").toString(),jo19.get("filling").toString(),jo19.get("high").toString(),jo19.get("lower").toString());
                                System.out.println("i:"+i+" k:"+k+" j:"+j+" z:"+z+" t:"+t);
                            }
//
                        }
                    }
                }

            }
        }
        System.out.println("执行完了");
    }


    @RequestMapping("getBookByIsbn")
    public String getBookByIsbn(String isbn,ModelMap map) throws IOException, InterruptedException {
        HttpClientUtil2 httpClientUtil2 = new HttpClientUtil2();
        Map<String,Object>params=new HashMap<>();
//        HttpResponse response = httpClientUtil2.HttoPost(params, "http://service.vin114.net/scripts/level.resources.js?t=20190329133610535");
        HttpResponse response=httpClientUtil2.httpGet("http://opac.nlc.cn/F/57XPVTCBVPS1DHMGTMR64LK95EF1SEXN6Y61N2XJ39CGIEET45-11945?func=find-b&find_code=ISB&request="+isbn+"&local_base=NLC01&filter_code_1=WLN&filter_request_1=&filter_code_2=WYR&filter_request_2=&filter_code_3=WYR&filter_request_3=&filter_code_4=WFM&filter_request_4=&filter_code_5=WSL&filter_request_5=");
        String str= null;
        try {
            str = EntityUtils.toString(response.getEntity(),"utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String bg="<!-- filename: full-999-body -->";
        String en="<!-- filename: full-set-tail -->";
        String str2=str.substring(str.indexOf(bg)+bg.length(),str.indexOf(en));
        map.addAttribute("tbody",str2);
//        while (getkey(str).equals("-1")){
//            System.out.println(getkey(str));
//        }
        return "showBookInfo";
    }
    public  String getkey(String s){
        int bgIndex=s.indexOf("p>")+2;
        int enIndex=s.indexOf("</td>");
        if (bgIndex!=0&&enIndex!=0){
            return s.substring(bgIndex,enIndex);
        }else {
            return "-1";
        }

    }
    @RequestMapping("activex")
    public String activex(){
        return "activex";
    }
    @RequestMapping("myActivex")
    public String myActivex(){
        return "myActivex";
    }
}